import time
from collections import OrderedDict
from datetime import datetime, timedelta
from types import FunctionType

from django.db.models import Q
from django.db.models import Sum
from django.http import JsonResponse
from django.shortcuts import render
from django.shortcuts import reverse
from django.utils.safestring import mark_safe

from web import models
from web.utils.group import get_incomma_value
from web.utils.pager import Pagernation


def get_attackip(text, field):
    """
    获取choice字段的文本
    :param text: choice字段的名称
    :param field: choice字段
    :return:
    """

    def inner(obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return text

        record_url = reverse('k01_attackip_list', kwargs={'pk': obj.id})
        tpl = '<a class="btn btn-info" href="{}">{:,}</a>'.format(record_url, obj.atkip_count)

        return mark_safe(tpl)

    return inner


def k01_list(request):
    list_display = [
        get_incomma_value('攻击数量', 'atk_count'),
        get_attackip('攻击IP数量', 'atkip_count'),
        'outgoing_count',
        'update_datetime',
    ]

    keyword = request.GET.get("keyword", "").strip()
    con = Q()
    if keyword:
        con.connector = "OR"
        con.children.append(('path__contains', keyword))
        con.children.append(('hostname__contains', keyword))
    queryset = models.K01.objects.all().order_by('-create_datetime')
    model_class = models.K01
    pager = Pagernation(request, queryset)
    # 1.处理表头
    header_list = []
    if list_display:
        for key_or_func in list_display:
            if isinstance(key_or_func, FunctionType):
                header_list.append(key_or_func(None, True))
            else:
                verbose_name = model_class._meta.get_field(key_or_func).verbose_name
                header_list.append(verbose_name)
    else:
        header_list.append(model_class._meta.model_name)
    # 2.处理表格内容
    data_list = queryset[pager.start:pager.end]
    body_list = []
    for row in data_list:
        tr_list = []
        if list_display:
            for key_or_func in list_display:
                if isinstance(key_or_func, FunctionType):
                    tr_list.append(key_or_func(row, False))
                else:
                    tr_list.append('' if getattr(row, key_or_func) == None else getattr(row, key_or_func))
        else:
            tr_list.append(row)
        body_list.append(tr_list)

    context = {
        'body_list': body_list,
        'header_list': header_list,
        'pager': pager,
        'keyword': keyword
    }
    return render(request, 'k01_list.html', context)


def get_data_dict(field, field_name):
    today = datetime.now().date() + timedelta(days=1)
    date_dict = OrderedDict()
    for i in range(0, 30):
        date = today - timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple()) * 1000, 0]
    queryset = models.K01.objects.filter(create_datetime__gt=today - timedelta(days=29)).extra(
        select={'ctime': "DATE_FORMAT(web_k01.create_datetime,'%%Y-%%m-%%d')"}).values('ctime').annotate(
        ct=Sum(field))
    for item in queryset:
        try:
            date_dict[item['ctime']][1] = item['ct']
        except Exception as e:
            print(item['ctime'], e)
        finally:
            continue
    return {'name': field_name, 'data': list(date_dict.values())}


def k01_account_chart(reqeust):
    account_mapping = {'atk_count': '攻击数量', 'atkip_count': '攻击IP数量'}
    data_list = []
    for k, v in account_mapping.items():
        data_list.append(get_data_dict(k, v))
    return JsonResponse({'status': True, 'data': data_list})


def attackip_list(request, pk):
    pass
